<?php

class Product extends Eloquent
{
	/**
	 * Specifies which attributes should be mass-assignable
	 * @var array
	 */
	protected $fillable = array('name', 'published');
	
	/*****************
	 * Relationships *
	 *****************/
	public function category()
	{
		return $this->belongsTo('Category');
	}
	
	public function seo()
	{
		return $this->morphMany('Seo', 'seoble');
	}
	
	public function reviews()
	{
		return $this->hasMany('Review');
	}
	
	/***************
	 * Query Scope *
	***************/
	/**
	 *
	 * @param unknown $query
	 */
	public function scopePublished($query)
	{
		return $query->where('published', true);
	}
	
	/**
	 *
	 * @param unknown $query
	 */
	public function scopeNotPublished($query)
	{
		return $query->where('published', false);
	}
	
	// The way average rating is calculated (and stored) is by getting an average of all ratings, 
	// storing the calculated value in the rating_cache column (so that we don't have to do calculations later)
	// and incrementing the rating_count column by 1
    public function recalculateRating($rating)
    {
    	$reviews = $this->reviews()->notSpam()->approved();
	    $avgRating = $reviews->avg('rating');
		$this->rating_cache = round($avgRating, 1);
		$this->rating_count = $reviews->count();
    	$this->save();
    }
}